﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace YJTMedicalAideManage.Cores.Helper
{

    public sealed class IniHelper
    {
        private static readonly Lazy<IniHelper> _instance = new Lazy<IniHelper>(() => new IniHelper());
        private IniHelper() { }

        public static IniHelper Instance => _instance.Value;

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        private static extern long WritePrivateProfileString(string section, string key, string value, string filePath);

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        private static extern int GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder retVal, int size, string filePath);

        /// <summary>
        /// 保存对象到指定的 INI 文件
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="obj">要保存的对象</param>
        /// <param name="section">INI 文件中的节名称</param>
        /// <param name="filePath">INI 文件路径</param>
        public void SaveToIni<T>(T obj, string section, string filePath)
        {
            // 确保目录存在
            var directory = Path.GetDirectoryName(filePath);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            // 遍历对象属性并保存到 INI 文件
            var properties = typeof(T).GetProperties();
            foreach (var property in properties)
            {
                var value = property.GetValue(obj)?.ToString() ?? string.Empty;
                WritePrivateProfileString(section, property.Name, value, filePath);
            }
        }
        public bool DoesFileExist(string filePath)
        {
            return File.Exists(filePath);
        }

        /// <summary>
        /// 从指定的 INI 文件读取对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="section">INI 文件中的节名称</param>
        /// <param name="filePath">INI 文件路径</param>
        /// <returns>读取的对象</returns>
        public T ReadFromIni<T>(string section, string filePath) where T : new()
        {
            var obj = new T();
            var properties = typeof(T).GetProperties();
            foreach (var property in properties)
            {
                var value = new StringBuilder(255);
                GetPrivateProfileString(section, property.Name, string.Empty, value, 255, filePath);
                if (property.PropertyType == typeof(int))
                {
                    property.SetValue(obj, int.Parse(value.ToString()));
                }
                else
                {
                    property.SetValue(obj, value.ToString());
                }
            }
            return obj;
        }

    }
}
